package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Contact;
import cn.wolfcode.crm.query.ContactQueryObject;
import cn.wolfcode.crm.service.IContactService;
import cn.wolfcode.crm.util.JsonResult;
import cn.wolfcode.crm.util.PageResult;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("contact")
public class ContactController {
    @Autowired
    private IContactService contactService;

    @RequiresPermissions(value = {"contact:view", "学校联系人视图"}, logical = Logical.OR)
    @RequestMapping("view")
    public String view() {
        return "contact/contact";
    }

    @RequiresPermissions(value = {"contact:query", "学校联系人列表"}, logical = Logical.OR)
    @RequestMapping("query")
    @ResponseBody
    public PageResult query(ContactQueryObject qo) {
        PageResult result = contactService.query(qo);
        return contactService.query(qo);
    }

    @RequiresPermissions(value = {"contact:selectAll", "学校联系人全选"}, logical = Logical.OR)
    @RequestMapping("selectAll")
    @ResponseBody
    public List<Contact> selectAll() {
        return contactService.selectAll();
    }

    @RequiresPermissions(value = {"contact:saveOrUpdate", "学校联系人编辑/新增"}, logical = Logical.OR)
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Contact entity) {
        try {
            if (entity.getId() == null) {
                contactService.insert(entity);
            } else {
                contactService.updateByPrimaryKey(entity);
            }
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult().mark("操作失败!原因:" + e.getMessage());
        }
    }


    @RequiresPermissions(value = {"contact:delete", "学校联系人删除"}, logical = Logical.OR)
    @RequestMapping("delete")
    @ResponseBody
    public JsonResult delete(Long id) {
        try {
            contactService.deleteByPrimaryKey(id);
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult().mark("操作失败!原因:" + e.getMessage());
        }
    }

    @RequestMapping("exportXls")
    @ResponseBody
    public void exportXls(HttpServletResponse response, ContactQueryObject qo) throws Exception {
        //设置文件下载响应头

        response.setHeader("Content-Disposition", "attachment;filename=Contact.xls");

        Workbook book = contactService.exportXls(qo);

        //写入数据输出到浏览器
        book.write(response.getOutputStream());
    }

}
